package com.ss.zsensm;

public class Serializing {
	private static byte[] list;
	private static int head = 0;
	private static int length = 0;
	private static boolean err = false;

	public static void empty() {
		head = 0;
		length = 0;
		err = false;
	}
	
	public static int hash(byte[] dat, int start, int end) {
		 int p = 16777619;
         int hash = (int)2166136261L;

         for (int i = start; i < end; i++)
             hash = (hash ^ (dat[i] & 0xff)) * p;

         hash += hash << 13;
         hash ^= hash >> 7;
         hash += hash << 3;
         hash ^= hash >> 17;
         hash += hash << 5;
         return hash;
	}

	public static int put(byte[] dat, int idx, float value) {
		return put(dat, idx, (int)Float.floatToRawIntBits(value));
	}
	
	public static int put(byte[] dat, int idx, String s) {
		idx = put(dat, idx, (int)s.length());
		if (idx < 0 || idx + s.length() > dat.length)
			return -1;
		for (int i = 0 ; i < s.length();i++){
			dat[i + idx] = (byte)s.charAt(i);
		}
		return idx + s.length();
	}
	
	public static int put(byte[] dat, int idx, int value) {
		if (idx + 3 > dat.length)
			return -1;
		dat[idx] = (byte) ((value >> 24) & 0xff);
		dat[idx + 1] = (byte) ((value >> 16) & 0xff);
		dat[idx + 2] = (byte) ((value >> 8) & 0xff);
		dat[idx + 3] = (byte) (value & 0xff);
		return idx + 4;
	}

	public static int put(byte[] dat, int idx, byte value) {
		if (idx + 1 > dat.length)
			return -1;
		dat[idx] = value;
		return idx + 1;
	}
	
	public static float getFloat(int idx){
		int x = getInt(idx);
		if (err)
			return 0.f;
		return Float.intBitsToFloat(x);
	}
	
	public static String getString(int idx){
		int len = getInt(idx);
		if (err)
			return null;
		idx = head;
		if (idx + len > length) {
			err = true;
			return null;
		}
		head += len;
		return new String(list, idx, len);
	}
	
	public static int getInt(int idx) {
		if (idx + 4 > length) {
			err = true;
			return 0;
		}
		head = idx + 4;
		return (((list[idx] << 24) & 0xff000000) | ((list[idx + 1] << 16) & 0xff0000) | ((list[idx + 2] << 8) & 0xff00) | ((list[idx + 3]) & 0xff));  
	}
	
	public static byte getByte(int idx) {
		if (idx < length) {
			head = idx + 1;
			return list[idx];
		}
		err = true;
		return (byte) 0;
	}
	
	public static int getInt() {
		return getInt(head);
	}
	
	public static byte getByte() {
		return getByte(head);
	}
	
	public static float getFloat() {
		return getFloat(head);
	}
	
	public static String getString() {
		return getString(head);
	}

	public static void shallowCopyFromByteArray(byte[] src, int _length) {
		list = src;
		head = 0;
		length = _length;
		err = false;
	}

	public static boolean error() {
		return err;
	}
}
